package cn.techwis.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.techwis.dto.QueryOrderDTO;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class WxAPIV3AesUtil {

    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;

    public static final byte[] WxAPIV3AesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        return key;
    }

    public final static QueryOrderDTO decryptToString(String apiv3key, String associatedData, String nonce, String ciphertext)
            throws GeneralSecurityException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] bytes = WxAPIV3AesUtil(apiv3key.getBytes());
            SecretKeySpec key = new SecretKeySpec(bytes, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData.getBytes());
            String s = new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
            if (StrUtil.isNotEmpty(s)) {
                QueryOrderDTO queryOrderDTO = JSONUtil.toBean(s, QueryOrderDTO.class);
                return queryOrderDTO;
            }
            return null;

        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

//    public static void main(String[] args) {
//        byte[] key =null;
//        WxAPIV3AesUtil aesUtil = new WxAPIV3AesUtil(key);
//        String decryptToString = aesUtil.decryptToString(assc.getBytes("UTF-8"),noce.getBytes("UTF-8"),cip);
//    }
}